package com.itheima.tliasmanagementspringboot.aspect;

import com.itheima.tliasmanagementspringboot.common.R;
import com.itheima.tliasmanagementspringboot.pojo.Emp;
import com.itheima.tliasmanagementspringboot.pojo.EmpLoginLog;
import com.itheima.tliasmanagementspringboot.pojo.FileUploadLog;
import com.itheima.tliasmanagementspringboot.service.EmpLoginLogService;
import com.itheima.tliasmanagementspringboot.service.FileUploadLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;

@Component
@Slf4j
@Aspect
public class UploadAspect {
    /*@Autowired
    HttpServletRequest httpServletRequest;*/
    @Autowired
    FileUploadLogService fileUploadLogService;

    @Around("execution(* com.itheima.tliasmanagementspringboot.controller.UploadController.*(..)) && @annotation(com.itheima.tliasmanagementspringboot.annotation.Log)")
    public Object loginAround(ProceedingJoinPoint pjp) throws Throwable {
        //1.前置
        System.out.println("文件上传前置");
        FileUploadLog fileUploadLog = new FileUploadLog();
        long start = System.currentTimeMillis();
        fileUploadLog.setUploadTime(LocalDateTime.now());
        //原始文件名
        //获取参数中的MultipartFile类型的参数image
        MultipartFile image = (MultipartFile)pjp.getArgs()[2];
        String originalFilename = image.getOriginalFilename();
        log.info("原始文件名: {}", originalFilename);//包含后缀
        fileUploadLog.setFilename(originalFilename);
        //文件大小
        log.info("文件大小: {}byte", image.getSize());//包含后缀
        fileUploadLog.setSize(image.getSize());
        //文件扩展名
        String fileExtname = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("文件扩展名: {}", fileExtname);//包含后缀
        fileUploadLog.setExtname(fileExtname);
        //执行原始方法
        Object result = pjp.proceed();
        R r = (R) result;
        long end = System.currentTimeMillis();
        fileUploadLog.setUrl((String)r.getData());
        fileUploadLogService.insert(fileUploadLog);
        return result;
    }

}
